package com.earthea.application.system.domain.service.impl;

import com.earthea.application.common.entity.TableDataInfo;
import com.earthea.application.common.utils.ip.AddressUtils;
import com.earthea.application.system.domain.entity.SysOperLog;
import com.earthea.application.system.domain.service.ISysOperLogService;
import com.earthea.application.system.entity.request.SysOperLogReq;
import com.earthea.application.system.mapper.SysOperLogMapper;
import com.google.common.base.Preconditions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * 操作日志 服务层处理
 */
@Service
public class SysOperLogServiceImpl implements ISysOperLogService {
    @Autowired
    private SysOperLogMapper operLogMapper;

    @Qualifier("singleExecute")
    @Autowired
    private ThreadPoolTaskExecutor singleExecute;

    /**
     * 新增操作日志
     *
     * @param operLog 操作日志对象
     */
    @Override
    public void insert(SysOperLog operLog) {
        // 远程查询操作地点
        String realAddressByIP = AddressUtils.getRealAddressByIP(operLog.getOperIp());
        CompletableFuture.runAsync(() -> {
            operLog.setOperLocation(realAddressByIP);
            operLogMapper.insert(operLog);
        }, singleExecute);
    }

    /**
     * 查询系统操作日志集合
     *
     * @param req 操作日志对象
     * @return 操作日志集合
     */
    @Override
    public TableDataInfo<SysOperLog> select(SysOperLogReq req) {
        Preconditions.checkNotNull(req, "req must be not null");
        int total = 0;
        if (req.isPage()) {
            total = operLogMapper.count(req);
            if (total == 0) {
                return TableDataInfo.EMPTY;
            }
        }
        return new TableDataInfo<>(total, operLogMapper.select(req));
    }

    /**
     * 批量删除系统操作日志
     *
     * @param operIds 需要删除的操作日志ID
     * @return 结果
     */
    @Override
    public int batchDelete(List<Long> operIds) {
        return operLogMapper.batchDelete(operIds);
    }

    /**
     * 清空操作日志
     */
    @Override
    public void clean() {
        operLogMapper.clean();
    }
}
